// Package log 基础日志组件
package log

import (
	"net"
	"os"

	"github.com/k0kubun/pp"
	isatty "github.com/mattn/go-isatty"
	"github.com/sirupsen/logrus"

	"gitee.com/familydoc/plugin/config"
)

// Logger logger
type Logger = *logrus.Entry

// Fields fields
type Fields = logrus.Fields

var Loger Logger

var ServerIP = localIP()

func init() {
	Loger = logrus.WithFields(logrus.Fields{
		"topic":       config.LogTopic,
		"app_name":    config.AppName,
		"server_host": config.AppAddr,
		"env":         config.Env,
		"server_ip":   ServerIP,
	})

	Loger.Logger.SetReportCaller(true)
}

func init() {
	setLogConfig()
	initPP()

	//是否配置kafka连接
	if config.IsSet("log.kafka") {
		kafka := config.GetStringSlice("log.kafka")

		NewKafkaHook(config.AppName, &logrus.JSONFormatter{}, kafka)
	}
}

func localIP() string {
	addrs, err := net.InterfaceAddrs()
	if err != nil {
		return ""
	}
	for _, address := range addrs {
		if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
			if ipnet.IP.To4() != nil {
				return ipnet.IP.String()
			}
		}
	}
	return ""
}

func setLogConfig() {
	logrus.SetFormatter(&logrus.TextFormatter{})
	if config.LogFormatter == "json" {
		logrus.SetFormatter(&logrus.JSONFormatter{})
	}

	//设置日志输出级别
	logLevel := getLogLevel(config.LogLevel)
	logrus.SetLevel(logLevel)
}

func getLogLevel(lvl string) logrus.Level {
	level, ok := logrus.ParseLevel(lvl)
	if ok == nil {
		return level
	}

	if config.IsDevEnv { // 开发环境设置为debug级别
		return logrus.DebugLevel
	}

	return logrus.ErrorLevel
}

func initPP() {
	out := os.Stdout
	pp.SetDefaultOutput(out)

	if !isatty.IsTerminal(out.Fd()) {
		pp.ColoringEnabled = false
	}
}

// PP 类似 PHP 的 var_dump
func PP(args ...interface{}) {
	pp.Println(args...)
}
